import * as THREE from 'three'
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import img from '../images/OIP-C.jpg'

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// 2. 加载纹理
var textureLoader = new THREE.TextureLoader();
var spriteTexture = textureLoader.load(img);

// 3. 创建精灵材质
var spriteMaterial = new THREE.SpriteMaterial({
    map: spriteTexture,
    color: 0xffffff,
    transparent: true // 如果你的图片有透明区域
});

// 4. 创建并配置精灵
var sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set(1, 1, 1); // 设置精灵的尺寸
sprite.position.set(0, 0, 0); // 设置精灵的位置

// 5. 添加精灵到场景中
scene.add(sprite);


// 设置相机控件轨道控制器OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
// 启用阻尼效果
controls.enableDamping = true;
controls.dampingFactor = 0.05;

// 如果OrbitControls改变了相机参数，重新调用渲染器渲染三维场景
controls.addEventListener("change", function () {
  renderer.render(scene, camera); //执行渲染操作
  // 浏览器控制台查看相机位置变化
  // console.log("camera.position", camera.position);
});

// 监听鼠标移动事件
document.addEventListener('mousemove', onDocumentMouseMove, false);

var mouseX = 0;
var mouseY = 0;

function onDocumentMouseMove(event) {
    mouseX = (event.clientX - window.innerWidth / 2) * 10;
    mouseY = -(event.clientY -  window.innerHeight / 2) * 10;
}


// 渲染循环
function animate() {
    requestAnimationFrame(animate);

    
    sprite.position.x = mouseX * 0.001;
    sprite.position.y = mouseY * 0.001;

    renderer.render(scene, camera);
}

animate();

window.onresize = function () {
  // 重置渲染器输出画布canvas尺寸
  renderer.setSize(window.innerWidth, window.innerHeight);
  // 全屏情况下：设置观察范围长宽比aspect为窗口宽高比
  camera.aspect = window.innerWidth / window.innerHeight;
  // 渲染器执行render方法的时候会读取相机对象的投影矩阵属性projectionMatrix
  // 但是不会每渲染一帧，就通过相机的属性计算投影矩阵(节约计算资源)
  // 如果相机的一些属性发生了变化，需要执行updateProjectionMatrix ()方法更新相机的投影矩阵
  camera.updateProjectionMatrix();
};